//
//  HouseDetailViewController.m
//  Fangmm
//
//  Created by 阮琦 on 16/3/1.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "HouseDetailViewController.h"
#import "CallServiceViewController.h"
#import "JoinRoomPopViewController.h"
#import "MapViewViewController.h"
#import "UserHomepageViewController.h"
#import "TwoButtonsPopViewController.h"
#import "FullWebViewController.h"
#import "CommunityDetailViewController.h"

#import "DetailTitleTableViewCell.h"
#import "RoomChiefListTableViewCell.h"
#import "RoomChiefTitleTableViewCell.h"
#import "HouseMessageTableViewCell.h"
#import "SupportMessageTableViewCell.h"
#import "CareTableViewCell.h"
#import "MapTableViewCell.h"

#import "DetailBarnerView.h"
#import "BottomView.h"
#import "AppDrawer.h"

#import "HttpServer.h"
#import "House.h"
#import "Seat.h"
#import "Team.h"
#import "FavoriteUser.h"
#import "Room.h"
#import "User.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/UIButton+WebCache.h>
#import <SDWebImageDownloader.h>
#import <TSMessages/TSMessageView.h>
#import "ACMacros.h"
#import "Constants.h"

#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "WXApi.h"
#import <MobClick.h>


@interface HouseDetailViewController () <UITableViewDataSource, UITableViewDelegate, DetailTitleTableViewCellDelegate, DetailBannerViewDelegate, BottomViewDelegate, MAMapViewDelegate, RoomChiefListTableViewCellDelegate, TwoButtonsViewDelegate, WXApiDelegate>

@end

@implementation HouseDetailViewController
{
    int numberOfLine;
    BOOL isFavorite;

    CGFloat detailTitleRowHeight;
    NSMutableArray *teams;
    NSMutableDictionary *favoriteData;
    NSString *favoriteId;
    NSMutableArray *roomAImages;
    NSMutableArray *roomBImages;
    NSMutableArray *roomCImages;
    NSMutableArray *roomImages;

    DetailBarnerView *banner;
    
    House *house;
    
    MAMapView *mapView;
    
    NSString *shareUrl;
    WXMediaMessage *shareMessage;
    
//    dispatch_source_t _timer;
}
-(void)viewWillAppear:(BOOL)animated
{
    [MobClick beginLogPageView:@"房源详情页"];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [MobClick endLogPageView:@"房源详情页"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configureNavigationBar];
    [self configureTableView];
    [self configureBottomView];
    [self configureAmap];
    [self loadHouseDetailData];
    [self loadHouseTeams];
    [self loadHouseFavorites];
    [self loadShareDatas];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - Configuring the view’s layout behavior
- (void)configureNavigationBar {
    self.title = @"房源详情";
    self.navigationItem.hidesBackButton = true;
    UIImage *backImage = [[UIImage imageNamed:@"back-18-36"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithImage:backImage style:UIBarButtonItemStyleDone target:self action:@selector(clickToPopBack)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    UIImage *shareImage = [[UIImage imageNamed:@"share-36-36"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithImage:shareImage style:UIBarButtonItemStyleDone target:self action:@selector(clickToShare)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    self.navigationItem.rightBarButtonItem = rightBarButton;
}

- (void)configureTableView {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height - 70) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setBackgroundColor:RGBACOLOR(71, 61, 61, 1)];
    detailTitleRowHeight = 190;
    banner = [[DetailBarnerView alloc]init];;
    banner = [[[NSBundle mainBundle] loadNibNamed:@"DetailBarnerView" owner:self options:nil] objectAtIndex:0];
    [banner setFrame:CGRectMake(0, 0, Main_Screen_Width, 307)];
    banner.delegate = self;
    roomAImages = [[NSMutableArray alloc]init];
    roomBImages = [[NSMutableArray alloc]init];
    roomCImages = [[NSMutableArray alloc]init];
    roomImages = [[NSMutableArray alloc]init];
    [self configureBanner];
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 50)];
    [self.tableView setTableHeaderView:banner];
    [self.tableView setTableFooterView:footer];
    [self.tableView registerNib:[UINib nibWithNibName:@"DetailTitleTableViewCell" bundle:nil] forCellReuseIdentifier:@"DetailTitleTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RoomChiefListTableViewCell" bundle:nil] forCellReuseIdentifier:@"RoomChiefListTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RoomChiefTitleTableViewCell" bundle:nil] forCellReuseIdentifier:@"RoomChiefTitleTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HouseMessageTableViewCell" bundle:nil] forCellReuseIdentifier:@"HouseMessageTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SupportMessageTableViewCell" bundle:nil] forCellReuseIdentifier:@"SupportMessageTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CareTableViewCell" bundle:nil] forCellReuseIdentifier:@"CareTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MapTableViewCell" bundle:nil] forCellReuseIdentifier:@"MapTableViewCell"];
}

- (void)configureBottomView {
    UIView *bottom = [[UIView alloc]initWithFrame:CGRectMake(0, Main_Screen_Height - 114, Main_Screen_Width, 50)];
    BottomView *bottomView = [[BottomView alloc]init];
    bottomView = [[[NSBundle mainBundle] loadNibNamed:@"BottomView" owner:self options:nil] objectAtIndex:0];
    bottomView.frame = CGRectMake(0, 0, Main_Screen_Width, 50);
    [self.view addSubview:bottom];
    bottomView.delegate = self;
    [bottom addSubview:bottomView];
}

- (void)configureBanner {
    if (house) {
        NSArray *buttonsArray = @[banner.room_A_Button, banner.room_B_Button, banner.room_C_Button];
        for (UIButton *button in buttonsArray) {
            button.hidden = true;
            button.titleLabel.numberOfLines = 2;
            button.titleLabel.textAlignment = NSTextAlignmentCenter;
        }
        banner.whole_Room_Button.titleLabel.numberOfLines = 2;
        banner.whole_Room_Button.titleLabel.textAlignment = NSTextAlignmentCenter;
        [banner.whole_Room_Button setTitle:[NSString stringWithFormat:@"%@\n%dm²", @"整套", house.area] forState:UIControlStateNormal];
        for (int i = 0; i < house.rooms.count; i++) {
            NSNumber *area = [house.rooms[i] objectForKey:@"area"];
            NSString *roomName = [house.rooms[i] objectForKey:@"name"];
            switch (i) {
                case 0:
                    [banner.room_A_Button setTitle:[NSString stringWithFormat:@"%@\n%@m²",roomName, area] forState:UIControlStateNormal];
                    banner.room_A_Button.hidden = false;
                    break;
                case 1:
                    [banner.room_B_Button setTitle:[NSString stringWithFormat:@"%@\n%@m²",roomName, area] forState:UIControlStateNormal];
                    banner.room_B_Button.hidden = false;
                    break;
                case 2:
                    [banner.room_C_Button setTitle:[NSString stringWithFormat:@"%@\n%@m²",roomName, area] forState:UIControlStateNormal];
                    banner.room_C_Button.hidden = false;
                    break;
                default:
                    break;
            }
        }
    }
    NSString *a = [banner.room_A_Button titleForState:UIControlStateNormal];
    NSString *b = [banner.room_B_Button titleForState:UIControlStateNormal];
    NSString *c = [banner.room_C_Button titleForState:UIControlStateNormal];
    for (id item in house.images) {
        NSString *classify = [item objectForKey:@"classify"];
        [roomImages addObject:[item objectForKey:@"path"]];
        if ([classify isEqual:a]) {
            [roomAImages addObject:[item objectForKey:@"path"]];
        } else if ([classify isEqual:b]) {
            [roomBImages addObject:[item objectForKey:@"path"]];
        } else if ([classify isEqual:c]) {
            [roomCImages addObject:[item objectForKey:@"path"]];
        }
    }
//    if (roomAImages.count == 0) {
//        [banner.room_A_Button setEnabled:false];
//        [banner.room_A_Button setTitle:@"暂无图片" forState:UIControlStateDisabled];
//    } else {
//        [banner.room_A_Button setEnabled:true];
//    }
//    if (roomBImages.count == 0) {
//        [banner.room_B_Button setEnabled:false];
//        [banner.room_B_Button setTitle:@"暂无图片" forState:UIControlStateDisabled];
//    } else {
//        [banner.room_B_Button setEnabled:true];
//    }
//    if (roomCImages.count == 0) {
//        [banner.room_C_Button setEnabled:false];
//        [banner.room_C_Button setTitle:@"暂无图片" forState:UIControlStateDisabled];
//    } else {
//        [banner.room_C_Button setEnabled:true];
//    }
    [banner.mainScrollView setScrollEnabled:true];
    [banner.mainScrollView setPagingEnabled:true];
    [banner refreshBannerWithImageUrls:roomImages];
}

- (void)configureAmap {
    [MAMapServices sharedServices].apiKey = kAmapKey;
    [AMapSearchServices sharedServices].apiKey = kAmapKey;
    mapView = [[MAMapView alloc]init];
    [mapView setZoomLevel:15.0 animated:false];
    mapView.delegate = self;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 3:
            if (teams.count == 0) {
                return 2;
            } else {
                return teams.count + 1;
            }
            break;
            
        default:
            return 1;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    switch (section) {
        case 0:
        {
            DetailTitleTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"DetailTitleTableViewCell"];
            cell.delegate = self;
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.houseTitleLabel setText:house.community];
            [cell.priceLabel setText:[NSString stringWithFormat:@"¥%d", house.singleRentFloor]];
            [cell.wholeRentLabel setText:[NSString stringWithFormat:@"(整租 ¥%d)", house.rent]];
            NSNumber *code = [[NSNumber alloc]initWithInteger:[[house.limits[0] objectForKey:@"code"] integerValue]];
            if ([code integerValue] == 1) {
                [cell.wholeRentLabel setHidden:true];
            } else {
                [cell.wholeRentLabel setHidden:false];
            }
            if (!house.region) {
                house.region = @"";
            }
            [cell.fromLabel setText:[NSString stringWithFormat:@"%@", house.from]];
            if (house.check) {
                [cell.checkLabel setHidden:false];
                cell.fromLabelLeading.constant = 30;
            } else {
                [cell.checkLabel setHidden:true];
                cell.fromLabelLeading.constant = 0;
            }
            
            [cell.houseInfoLabel setText:[NSString stringWithFormat:@"%@ %d室%d厅%d卫 - %dm² | 入住时间: %@",house.region, house.roomNum, house.hallNum, house.toiletNum, house.area, house.checkinTime]];
            [cell.panoramaButton addTarget:self action:@selector(clickToPanorama) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
            break;
        case 1:
        {
            HouseMessageTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"HouseMessageTableViewCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.roomAView setHidden:true];
            [cell.roomBView setHidden:true];
            [cell.roomCView setHidden:true];
            [cell.houseId setText:house.sourceNo];
            [cell.houseDirection setText:house.orientation];
            if (house.floorSection == nil) {
                house.floorSection = @"";
            }
            [cell.houseFloor setText:[NSString stringWithFormat:@"%@/%d", house.floorSection, house.floorTotal]];
            [cell.tolietNumber setText:[NSString stringWithFormat:@"%d卫", house.toiletNum]];
            [cell.renovate setText:house.style];
            [cell.years setText:house.decade];
            [cell.payWay setText:house.paymode];
            for (int i = 0; i < house.rooms.count; i++) {
                id room = house.rooms[i];
                NSString *name = [room objectForKey:@"name"];
                NSNumber *area = (NSNumber *)[room objectForKey:@"area"];
                NSArray *facilities = [room objectForKey:@"facilities"];
                NSString *facility;
                for (id item in facilities) {
                    if ([facilities isEqual:@""] || facility == nil) {
                        facility = [item objectForKey:@"name"];
                    } else {
                        facility = [NSString stringWithFormat:@"%@ | %@",facility, [item objectForKey:@"name"]];
                    }
                }
                if (facilities == nil || facilities.count == 0) {
                    facility = @"无";
                }
                if (house.rooms.count <= 3) {
                    if (i == 0) {
                        [cell.roomAView setHidden:false];
                        [cell.roomANameLabel setText:[NSString stringWithFormat:@"%@",name]];
                        [cell.roomAAreaLabel setText:[NSString stringWithFormat:@"面积: %@m²",area]];
                        [cell.roomAFacilities setText:[NSString stringWithFormat:@"设施: %@",facility]];
                    } else if (i == 1) {
                        [cell.roomBView setHidden:false];
                        [cell.roomBNameLabel setText:[NSString stringWithFormat:@"%@",name]];
                        [cell.roomBAreaLabel setText:[NSString stringWithFormat:@"面积: %@m²",area]];
                        [cell.roomBFacilities setText:[NSString stringWithFormat:@"设施: %@",facility]];
                    } else if (i == 2) {
                        [cell.roomCView setHidden:false];
                        [cell.roomCNameLabel setText:[NSString stringWithFormat:@"%@",name]];
                        [cell.roomCAreaLabel setText:[NSString stringWithFormat:@"面积: %@m²",area]];
                        [cell.roomCFacilities setText:[NSString stringWithFormat:@"设施: %@",facility]];
                    }
                }
            }

            return cell;
        }
            break;
        case 2:
        {
            SupportMessageTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"SupportMessageTableViewCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            NSArray *btnArray = @[cell.btn_1, cell.btn_2, cell.btn_3, cell.btn_4, cell.btn_5, cell.btn_6, cell.btn_7, cell.btn_8, cell.btn_9, cell.btn_10];
            NSArray *labelArray = @[cell.label_1, cell.label_2, cell.label_3, cell.label_4, cell.label_5, cell.label_6, cell.label_7, cell.label_8, cell.label_9, cell.label_10];
            NSMutableArray *facilities = [NSMutableArray arrayWithArray:house.facilities];
            for (int i = 0; i < facilities.count; i++) {
                id data = house.facilities[i];
                NSNumber *count = [data objectForKey:@"count"];
                if (![count boolValue]) {
                    [facilities removeObjectAtIndex:i];
                } else {
                }
            }
            for (int i = 0; i < facilities.count; i++) {
                UILabel *label = labelArray[i];
                UIButton *button = btnArray[i];
                id data = house.facilities[i];
                [label setText:[data objectForKey:@"name"]];
                [button setBackgroundImage:[UIImage imageNamed:@"selected40-40"] forState:UIControlStateNormal];
            }
            return cell;
        }
            break;
        case 3:
        {
            NSNumber *code = [[NSNumber alloc]initWithInteger:[[house.limits[0] objectForKey:@"code"] integerValue]];
            if ([code integerValue] == 1) {
                UITableViewCell *cell = [[UITableViewCell alloc]init];
                return cell;
            } else {
                switch (row) {
                    case 0:
                    {
                        [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
                        RoomChiefTitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RoomChiefTitleTableViewCell"];
                        [cell.chiefButton addTarget:self action:@selector(clickToBecomeChief) forControlEvents:UIControlEventTouchUpInside];
                        cell.selectionStyle = UITableViewCellSelectionStyleNone;
                        [cell.roomALabel setHidden:true];
                        [cell.roomBLabel setHidden:true];
                        [cell.roomCLabel setHidden:true];
                        for (int i = 0; i < house.rooms.count; i++) {
                            switch (i) {
                                case 0:
                                    [cell.roomALabel setHidden:false];
                                    break;
                                case 1:
                                    [cell.roomBLabel setHidden:false];
                                    break;
                                case 2:
                                    [cell.roomCLabel setHidden:false];
                                    break;
                                    
                                default:
                                    break;
                            }
                        }
                        return cell;
                    }
                        break;
                    default:
                    {
                        if (teams.count != 0) {
                            
                            NSInteger row = indexPath.row - 1;
                            Team *team = [[Team alloc]initWithDic:teams[row]];
                            NSArray *seats = team.seats;
                            RoomChiefListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RoomChiefListTableViewCell"];
                            [cell setDelegate:self];
                            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(10, 104.3, Main_Screen_Width - 20, 0.7)];
                            [line setBackgroundColor:RGBACOLOR(240, 240, 240, 0.8)];
                            [cell addSubview:line];
                            cell.selectionStyle = UITableViewCellSelectionStyleNone;
                            [cell.aChooseButton setTitle:@"空闲" forState:UIControlStateNormal];
                            [cell.bChooseButton setTitle:@"空闲" forState:UIControlStateNormal];
                            [cell.cChooseButton setTitle:@"空闲" forState:UIControlStateNormal];
                            [cell.aChooseButton setTitleColor:RGBCOLOR(160, 160, 160) forState:UIControlStateNormal];
                            [cell.bChooseButton setTitleColor:RGBCOLOR(160, 160, 160) forState:UIControlStateNormal];
                            [cell.cChooseButton setTitleColor:RGBCOLOR(160, 160, 160) forState:UIControlStateNormal];
                            [cell.aChooseButton.layer setBorderColor:[RGBCOLOR(160, 160, 160) CGColor]];
                            [cell.bChooseButton.layer setBorderColor:[RGBCOLOR(160, 160, 160) CGColor]];
                            [cell.cChooseButton.layer setBorderColor:[RGBCOLOR(160, 160, 160) CGColor]];
                            [cell.aChooseButton setUserInteractionEnabled:false];
                            [cell.bChooseButton setUserInteractionEnabled:false];
                            [cell.cChooseButton setUserInteractionEnabled:false];
                            cell.team = team;
                            cell.tag = row;
                            [self actionTimer:cell];
                            [cell.numberLabel setText:[NSString stringWithFormat:@"%ld.",row + 1]];
                            [cell.aChooseButton setHidden:true];
                            [cell.bChooseButton setHidden:true];
                            [cell.cChooseButton setHidden:true];
                            for (int i = 0; i < seats.count; i++) {
                                Seat *seat = [[Seat alloc]initWithDic:seats[i]];
                                switch (i) {
                                    case 0:
                                        [cell.aChooseButton setHidden:false];
                                        if (!(seat.userId == nil || [seat.userId isEqual:@""])) {
                                            [cell.aAvatarButton sd_setBackgroundImageWithURL:[NSURL URLWithString:seat.userAvatar] forState:UIControlStateNormal];
                                            if (seat.leader) {
                                                [cell.aChooseButton setTitle:@"室长" forState:UIControlStateNormal];
                                                [cell.aChooseButton setTitleColor:RGBACOLOR(255, 118, 108, 1) forState:UIControlStateNormal];
                                            } else {
                                                [cell.aChooseButton setTitle:@"室友" forState:UIControlStateNormal];
                                                [cell.aChooseButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                                            }
                                            [cell.aNameLabel setText:seat.userName];
                                            if ([seat.userGender isEqual:@"f"]) {
                                                [cell.aGenderImageView setImage:[UIImage imageNamed:@"girl_22-22"]];
                                            } else {
                                                [cell.aGenderImageView setImage:[UIImage imageNamed:@"boy_22-22"]];
                                            }
                                            cell.aPriceLabel.hidden = true;
                                        } else {
                                            cell.aPriceLabel.hidden = false;
                                            [cell.aPriceLabel setText:[NSString stringWithFormat:@"%d元/月",seat.rent]];
                                        }
                                        break;
                                    case 1:
                                        [cell.bChooseButton setHidden:false];
                                        if (!(seat.userId == nil || [seat.userId isEqual:@""])) {
                                            [cell.bAvatarButton sd_setBackgroundImageWithURL:[NSURL URLWithString:seat.userAvatar] forState:UIControlStateNormal];
                                            if (seat.leader) {
                                                [cell.bChooseButton setTitle:@"室长" forState:UIControlStateNormal];
                                                [cell.bChooseButton setTitleColor:RGBACOLOR(255, 118, 108, 1) forState:UIControlStateNormal];
                                            } else {
                                                [cell.bChooseButton setTitle:@"室友" forState:UIControlStateNormal];
                                                [cell.bChooseButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                                            }
                                            [cell.bNameLabel setText:seat.userName];
                                            if ([seat.userGender isEqual:@"f"]) {
                                                [cell.bGenderImageView setImage:[UIImage imageNamed:@"girl_22-22"]];
                                            } else {
                                                [cell.bGenderImageView setImage:[UIImage imageNamed:@"boy_22-22"]];
                                            }
                                            cell.bPriceLabel.hidden = true;
                                        } else {
                                            cell.bPriceLabel.hidden = false;
                                            [cell.bPriceLabel setText:[NSString stringWithFormat:@"%d元/月",seat.rent]];
                                        }
                                        break;
                                    case 2:
                                        [cell.cChooseButton setHidden:false];
                                        if (!(seat.userId == nil || [seat.userId isEqual:@""])) {
                                            [cell.cAvatarButton sd_setBackgroundImageWithURL:[NSURL URLWithString:seat.userAvatar] forState:UIControlStateNormal];
                                            if (seat.leader) {
                                                [cell.cChooseButton setTitle:@"室长" forState:UIControlStateNormal];
                                                [cell.cChooseButton setTitleColor:RGBACOLOR(255, 118, 108, 1) forState:UIControlStateNormal];
                                            } else {
                                                [cell.cChooseButton setTitle:@"室友" forState:UIControlStateNormal];
                                                [cell.cChooseButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                                            }
                                            [cell.cNameLabel setText:seat.userName];
                                            if ([seat.userGender isEqual:@"f"]) {
                                                [cell.cGenderImageView setImage:[UIImage imageNamed:@"girl_22-22"]];
                                            } else {
                                                [cell.cGenderImageView setImage:[UIImage imageNamed:@"boy_22-22"]];
                                            }
                                            cell.cPriceLabel.hidden = true;
                                        } else {
                                            cell.cPriceLabel.hidden = false;
                                            [cell.cPriceLabel setText:[NSString stringWithFormat:@"%d元/月",seat.rent]];
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                            return cell;
                        } else {
                            UITableViewCell *emptyCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"emptyCell"];
                            [emptyCell setSelectionStyle:UITableViewCellSelectionStyleNone];
                            [emptyCell.textLabel setText:@"暂无室友小组,快来成为室长创建小组吧!"];
                            [emptyCell.textLabel setTextColor:RGBCOLOR(71, 62, 58)];
                            [emptyCell.textLabel setFont:[UIFont systemFontOfSize:15]];
                            return emptyCell;
                        }
                        
                    }
                        break;
                }
            }
        }
            break;
        case 4:
        {
            MapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MapTableViewCell"];
            [mapView setFrame:cell.mapSupportView.bounds];
            mapView.showsUserLocation = true;
            [mapView setCenterCoordinate:CLLocationCoordinate2DMake(house.gpsLat,house.gpsLng)];
            [mapView setZoomLevel:15 animated:true];
            
            MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
            pointAnnotation.coordinate = CLLocationCoordinate2DMake(house.gpsLat,house.gpsLng);
            pointAnnotation.title = @"小区位置";

            [mapView addAnnotation:pointAnnotation];            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.mapSupportView addSubview:mapView];
            return cell;
        }
            break;
        case 5:
        {
            CareTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"CareTableViewCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            NSArray *imageViews = @[cell.headerImage_1, cell.headerImage_2, cell.headerImage_3, cell.headerImage_4, cell.headerImage_5];
            [cell.carePersonNumLabel setText:[NSString stringWithFormat:@"%@",[favoriteData objectForKey:@"count"]]];
            if ([favoriteData objectForKey:@"count"] == nil) {
                [cell.carePersonNumLabel setText:@"0"];
            }
            NSArray *users = [favoriteData objectForKey:@"users"];
            for (int i = 0; i < users.count; i++) {
                [imageViews[i] sd_setImageWithURL:[NSURL URLWithString:[users[i] objectForKey:@"userAvatar"]]];
            }
            cell.carePersonNumLabel.layer.borderColor = [RGBACOLOR(204, 204, 204, 1) CGColor];
            return cell;
        }
            break;

        default:
        {
            UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            return cell;

        }
            break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 6;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    switch (section) {
        case 0:
            return detailTitleRowHeight;
            break;
        case 1:
            if (house.rooms.count == 1) {
                return 160;
            } else if (house.rooms.count == 2) {
                return 190;
            } else if (house.rooms.count == 3) {
                return 220;
            } else {
                return 130;
            }
            break;
        case 2:
            return 150;
            break;
        case 3:
        {
            NSNumber *code = [[NSNumber alloc]initWithInteger:[[house.limits[0] objectForKey:@"code"] integerValue]];
            if ([code integerValue] == 1) {
                return 0;
            } else {
                switch (row) {
                    case 0:
                        return 80;
                        break;
                        
                    default:
                        return 105;
                        break;
                }
            }
        }
            break;
        case 4:
            return 225;
            break;
        case 5:
            return 55;
            break;
        default:
            return 0;
            break;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    if (section == 4) {
        MapViewViewController *newMapView = [[MapViewViewController alloc]init];
        newMapView.Latitude = house.gpsLat;
        newMapView.Longitude = house.gpsLng;
        [self.navigationController pushViewController:newMapView animated:true];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc]init];
    [footerView setBackgroundColor:RGBACOLOR(71, 61, 61, 1)];
    return footerView;
}

#pragma mark - BottomViewDelegate
-(void)clickedServicePhoneButton
{
    CallServiceViewController *customerService = [[CallServiceViewController alloc]init];
    [self presentViewController:customerService animated:YES completion:nil];
}
-(void)clickedCommunityButton
{
    CommunityDetailViewController *communityMessageVC = [[CommunityDetailViewController alloc]init];
#pragma communityID
    communityMessageVC.communityId = house.communityId;
    [self.navigationController pushViewController:communityMessageVC animated:YES];
}

-(void)clickedJoinRoomButton
{
    if (house == nil) {
        
    } else {
        if (house.limits && house.limits.count != 0) {
            [self requestToFavorHouse];
            NSNumber *code = [[NSNumber alloc]initWithInteger:[[house.limits[0] objectForKey:@"code"] integerValue]];
            if ([code integerValue] == 1) {
                CallServiceViewController *customerService = [[CallServiceViewController alloc]init];
                customerService.contactPhoneNumber = house.contactMobile;
                [self presentViewController:customerService animated:YES completion:^{
                    
                }];
            }
        } else {
            NSLog(@"加入房间");
            JoinRoomPopViewController *joinRoomVC = [[JoinRoomPopViewController alloc]initWithNibName:@"JoinRoomPopViewController" bundle:nil];
            joinRoomVC.house = house;
            joinRoomVC.teamsData = teams;
            [self presentViewController:joinRoomVC animated:true completion:^{
            }];
        }
    }
}


#pragma mark - Triggering Methods
- (void)clickToPopBack {
    [self.navigationController popViewControllerAnimated:true];
}

- (void)clickToShare {
    TwoButtonsPopViewController *twoButtonsVC = [[TwoButtonsPopViewController alloc]initWithNibName:@"TwoButtonsPopViewController" bundle:nil];
    [twoButtonsVC setDelegate:self];
    [self presentViewController:twoButtonsVC animated:true completion:^{
        twoButtonsVC.sourceView = @"Share";
        [twoButtonsVC.titleLabel setText:@"分享房源"];
        [twoButtonsVC.firstButton setBackgroundImage:[UIImage imageNamed:@"wechat"] forState:UIControlStateNormal];
        [twoButtonsVC.firstLabel setText:@""];
        [twoButtonsVC.secondButton setBackgroundImage:[UIImage imageNamed:@"fb"] forState:UIControlStateNormal];
        [twoButtonsVC.secondLabel setText:@""];
    }];
}

- (void)clickToMapView {
    MapViewViewController *newMapView = [[MapViewViewController alloc]init];
    [self.navigationController pushViewController:newMapView animated:true];
}

- (void)clickToBecomeChief {
    
}

#pragma mark - Network methods
- (void)loadHouseDetailData {
    if (self.houseId == nil || [self.houseId isEqual:@""]) {
        NSLog(@"houseId is nil");
    } else {
        [HttpServer getHouseDetailWithHouseId:self.houseId WithSuccessBlock:^(NSDictionary *houseData) {
            house = [[House alloc]initWithDic:[houseData objectForKey:@"house"]];
            [self.tableView reloadData];
            [self configureBanner];
        } withFailBlock:^(id failData) {
            NSLog(@"%@",failData);
        }];
    }
}

- (void)loadHouseTeams {
    if (self.houseId == nil || [self.houseId isEqual:@""]) {
        NSLog(@"houseId is nil");
    } else {
        [HttpServer getHouseTeamsWithHouseId:self.houseId WithSuccessBlock:^(NSDictionary *teamsData) {
            teams = [NSMutableArray arrayWithArray:[teamsData objectForKey:@"teams"]];
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationAutomatic];
        } withFailBlock:^(id failData) {
            NSLog(@"%@",failData);
        }];
    }
}

//- (void)loadUserTeams {
//    User *user = [User sharedUser];
//    if (user.userId == nil || [user.userId isEqual:@""]) {
//        NSLog(@"houseId is nil");
//    } else {
//        [HttpServer getRoomMateTeamWithUserId:user.userId withStatus:@"" withPage:1 withPageSize:10 withUserInfo:@{@"excludes":@"house,applyNum", @"houseId":self.houseId} withSuccessBlock:^(NSDictionary *successDic) {
//            roommatesArray =[[NSMutableArray alloc]initWithArray:[successDic objectForKey:@"teams"]];
//            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
//        } withFailedBlock:^(id failData) {
//            NSLog(@"%@",failData);
//        }];
//    }
//}

- (void)loadHouseFavorites {
    if (self.houseId == nil || [self.houseId isEqual:@""]) {
        NSLog(@"houseId is nil");
    } else {
        [HttpServer getHouseFavoritesWithHouseId:self.houseId withParams:nil WithSuccessBlock:^(NSDictionary *favoritesData) {
            favoriteData = [[NSMutableDictionary alloc]initWithDictionary:favoritesData];
            if ([[favoriteData allKeys]containsObject:@"favorite"]) {
                isFavorite = true;
                favoriteId = [[favoriteData objectForKey:@"favorite"] objectForKey:@"favoriteId"];
            } else {
                isFavorite = false;
                favoriteId = @"";
            }
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:5] withRowAnimation:UITableViewRowAnimationAutomatic];
            if (isFavorite) {
                [banner.likeButton setBackgroundImage:[UIImage imageNamed:@"detail_like_click"] forState:UIControlStateNormal];
            } else {
                [banner.likeButton setBackgroundImage:[UIImage imageNamed:@"detail_like_non"] forState:UIControlStateNormal];
            }
        } withFailBlock:^(id failData) {
            NSLog(@"%@",failData);
        }];
    }
}

- (void)loadShareDatas {
    if (self.houseId == nil || [self.houseId isEqual:@""]) {
    } else {
        [HttpServer getSharelinksWithType:@"house" sharedInfo:self.houseId WithSuccessBlock:^(NSDictionary *successDic) {
            shareUrl = [successDic objectForKey:@"link"];
            shareMessage = [self wechateShareData:successDic];
        } withFailedBlock:^(id failData) {
            NSLog(@"%@",failData);
        }];
    }
}

- (WXMediaMessage *)wechateShareData:(NSDictionary *)successDic {
    WXMediaMessage *message = [[WXMediaMessage alloc]init];
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:[successDic objectForKey:@"thumbnail"]] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        message.thumbData = data;
    }];
    message.title = [successDic objectForKey:@"title"];
    message.description = [successDic objectForKey:@"description"];
    return message;
}

- (void)requestToFavorHouse {
    if (self.houseId == nil || [self.houseId isEqual:@""]) {
        NSLog(@"houseId is nil");
    } else {
        [HttpServer postToFavorHouseWithHouseId:self.houseId WithSuccessBlock:^(NSDictionary *favoritesData) {
            isFavorite = true;
            favoriteId = [[favoritesData objectForKey:@"favorite"] objectForKey:@"favoriteId"];
            [banner.likeButton setBackgroundImage:[UIImage imageNamed:@"detail_like_click"] forState:UIControlStateNormal];
            [TSMessage showNotificationInViewController:[AppDrawer sharedDrawer] title:@"收藏成功!" subtitle:@"您已成功收藏该房源" type:TSMessageNotificationTypeSuccess duration:2.0 canBeDismissedByUser:true];
        } withFailBlock:^(id failData) {
            NSLog(@"%@",failData);
        }];
    }
}

- (void)requestToDeleteFavorite {
    if (favoriteId == nil || [favoriteId isEqual:@""]) {
        NSLog(@"favoriteId is nil");
    } else {
        [HttpServer deleteFavoriteHouseWithId:favoriteId WithSuccessBlock:^(NSDictionary *successDic) {
            isFavorite = false;
            favoriteId = @"";
            [banner.likeButton setBackgroundImage:[UIImage imageNamed:@"detail_like_non"] forState:UIControlStateNormal];
        } withFailBlock:^(id failData) {
            NSLog(@"%@",failData);
        }];
    }
}
#pragma mark - Detail banner view delegate
- (void)buttonClicked:(UIButton *)sender {
    if ([sender isEqual:banner.likeButton]) {
        if (isFavorite) {
            [self requestToDeleteFavorite];
        } else {
            [self requestToFavorHouse];
        }
    } else if ([sender isEqual:banner.room_A_Button]) {            [banner refreshBannerWithImageUrls:roomAImages];
    } else if ([sender isEqual:banner.room_B_Button]) {
        [banner refreshBannerWithImageUrls:roomBImages];
    } else if ([sender isEqual:banner.room_C_Button]) {
        [banner refreshBannerWithImageUrls:roomCImages];
    } else if ([sender isEqual:banner.whole_Room_Button]) {
        [banner refreshBannerWithImageUrls:roomImages];
    }
}

#pragma mark - Amap delegate
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    if(updatingLocation)
    {
        //取出当前位置的坐标
        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
    }
}

//#pragma mark - Room chief list delegate
//- (void)clickToChooseRoom:(NSString *)roomName WithSeatId:(NSString *)seatId InTeam:(NSString *)teamId WithRent:(int)rent {
//    JoinRoomPopViewController *joinRoomVC = [[JoinRoomPopViewController alloc]initWithNibName:@"JoinRoomPopViewController" bundle:nil];
//    joinRoomVC.house = house;
//    joinRoomVC.teamsData = teams;
//    joinRoomVC.userTeam = roommatesArray;
//    [self presentViewController:joinRoomVC animated:true completion:^{
//        [joinRoomVC selectedSeatWithSeatId:seatId TeamId:teamId RoomName:roomName AndRent:rent];
//    }];
//}

- (void)clickToShowUserMainInfoWithTag:(NSInteger)tag WithIndex:(NSInteger)index {
    Team *team = [[Team alloc]initWithDic:teams[index]];
    Seat *seat = [[Seat alloc]initWithDic:team.seats[tag]];
    UserHomepageViewController *userHomepageVC = [[UserHomepageViewController alloc]init];
    userHomepageVC.userId = seat.userId;
    userHomepageVC.userName = seat.userName;
    [self.navigationController pushViewController:userHomepageVC animated:true];
}

#pragma mark - Two buttons view delegate
- (void)sharebuttonClickedWithTag:(NSInteger)tag {
    if ([WXApi isWXAppSupportApi]) {
        NSLog(@"true");
    } else {
        NSLog(@"false");
    }
    SendMessageToWXReq *shareReq;
    shareReq = [[SendMessageToWXReq alloc]init];
    shareReq.bText = false;
    shareReq.message = shareMessage;
    WXWebpageObject *webObj = [[WXWebpageObject alloc]init];
    webObj.webpageUrl = shareUrl;
    shareReq.message.mediaObject = webObj;
    switch (tag) {
        case 0:
        {
            shareReq.scene = 0;
            [WXApi sendReq:shareReq];
            [self dismissViewControllerAnimated:true completion:^{
            }];
        }
            break;
            
        default:
        {
            shareReq.scene = 1;
            [WXApi sendReq:shareReq];
            [self dismissViewControllerAnimated:true completion:^{
            }];

        }
            break;
    }
}

#pragma mark - Timer methods
- (void)actionTimer:(RoomChiefListTableViewCell *)cell {
    Team *team = cell.team;
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *expireDate = [dateFormatter dateFromString:team.expireTime];
    NSDate *startDate = [NSDate date];
    NSTimeInterval timeInterval =[expireDate timeIntervalSinceDate:startDate];
    
    dispatch_source_t _timer;
    if (_timer==nil) {
        __block int timeout = timeInterval; //倒计时时间
        
        if (timeout!=0) {
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
//                    _timer = nil;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [cell.timeLabel setText:@"报价已失效"];
//                        self.dayLabel.text = @"";
//                        self.hourLabel.text = @"00";
//                        self.minuteLabel.text = @"00";
//                        self.secondLabel.text = @"00";
                    });
                }else{
                    int days = (int)(timeout/(3600*24));
//                    if (days==0) {
//                        self.dayLabel.text = @"";
//                    }
                    int hours = (int)((timeout-days*24*3600)/3600);
                    int minute = (int)(timeout-days*24*3600-hours*3600)/60;
                    int second = timeout-days*24*3600-hours*3600-minute*60;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (days == 0) {
                            [cell.timeLabel setText:[NSString stringWithFormat:@"%d时%d分%d秒后报价失效",hours, minute, second]];
                            if (hours == 0) {
                                [cell.timeLabel setText:[NSString stringWithFormat:@"%d分%d秒后报价失效",minute, second]];
                                if (minute == 0) {
                                    [cell.timeLabel setText:[NSString stringWithFormat:@"%d秒后报价失效", second]];
                                }
                            }
                        }else{
                            [cell.timeLabel setText:[NSString stringWithFormat:@"%d天%d时%d分%d秒后报价失效",days, hours, minute, second]];
                        }
                    });
                    timeout--;
                }
            });
            dispatch_resume(_timer);
        }
    }

}

- (void)onReq:(BaseReq *)req {
    
}

- (void)clickToPanorama {
    FullWebViewController *webVC = [[FullWebViewController alloc]init];
    webVC.destinationUrl = [NSString stringWithFormat:@"http://m.fangmm.com/app/client/panoramic/%@",self.houseId];
    [self.navigationController pushViewController:webVC animated:true];
}

@end
